package com.codeczx.customnotificationdemo;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

public class TestService extends Service {

    private static final String TAG = "TestService";
    public static final String REQUEST_CODE = "request_code";
    public static final int CLICK = 1;

    private RemoteViews remoteViews;
    private NotificationCompat.Builder builder;
    private NotificationManager notificationManager;
    private static final int NOTIFY_ID = 1;

    public TestService(){}

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int requestCode = intent.getIntExtra(REQUEST_CODE, 0);
        if (requestCode == CLICK) {
            remoteViews.setTextViewText(R.id.tv_content, "已点击");
            notificationManager.notify(NOTIFY_ID, builder.build());
        } else {
            setCustomNotification();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void setCustomNotification() {
        builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        remoteViews = new RemoteViews("com.codeczx.customnotificationdemo", R.layout.notification);
        Intent intent = new Intent(TestService.this, TestService.class);
        intent.putExtra(REQUEST_CODE, CLICK);
        PendingIntent PI = PendingIntent.getService(this, CLICK, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.iv_large_icon, PI);
        builder.setContent(remoteViews);
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFY_ID, builder.build());
    }
}
